package cn.xianyang._04_tran;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.List;

public class Consumer {
    public static void main(String[] args) throws Exception {
        //创建消费者，以推送的方式MQPush消费消息
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("hello_consumer_group4");
        //消费者连接mq
        consumer.setNamesrvAddr("localhost:9876");

        //绑定监听的 topic 和 tag
        consumer.subscribe("hello_topic_Test4" /* Topic */,"hello_tags_Test4");

        //在注册监听器，消费消息
        consumer.registerMessageListener(new MessageListenerConcurrently(){
            //消费消息
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,ConsumeConcurrentlyContext context) {
                try {
                    for (MessageExt msg : msgs) {
                        String result = new String(msg.getBody(), RemotingHelper.DEFAULT_CHARSET);
                        System.out.println(result);
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });
        //开启消费者
        consumer.start();
    }
}
